<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/3/19
  Time: 21:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
    <title>这是index</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../styles/bootstrap.min.css" type="text/css"/>
    <link rel="stylesheet" href="../styles/toastr.min.css">
    <script src="../scripts/jquery.js" type="text/javascript"></script>
    <script src="../scripts/bootstrap.js" type="text/javascript"></script>
    <script src="../scripts/toastr.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
    <table class="table table-hover table-bordered" id="mTable">
        <tbody>
        <tr>
            <td></td>
            <td></td>
            <td width="15%">标题</td>
            <td width="25%">网址</td>
            <td width="8%" align="center">访问间隔(秒)</td>
            <td width="8%" align="center">超时时间(秒)</td>
            <td width="8%" align="center">访问时间</td>
            <td width="10%" align="center">访问次数</td>
            <td align="center">操作</td>
        </tr>
        </tbody>
        <c:forEach items="${lists}" var="item">
            <tr>
                <td><input type="checkbox" name="cb"></td>
                <td><img width="20" height="20" id="img_status" src="../files/img/status_red.png">
                </td>
                <td width="15%">${item.title_name }</td>
                <td width="25%">${item.url }</td>
                <td width="8%" align="center">${item.access_time_interval }</td>
                <td width="8%" align="center">${ item.time_out }</td>
                <td width="8%" align="center">
                    <c:choose>
                        <c:when test="${item.access_time == '1'}">
                            全部
                        </c:when>
                        <c:otherwise>
                            ${item.access_time }
                        </c:otherwise>
                    </c:choose></td>
                <td width="10%" align="center" id="access_times">${ item.access_times }</td>
                <td align="center">
                    <input type="hidden" value="${item.id }" id="hidden_id"/>
                    <input type="hidden" value="${item.is_green}" id="hidden_is_green"/>
                    <c:choose>
                        <c:when test="${ item.is_run == 1 }">
                            <input type="button" value="暂停"
                                   class="btn" id="btnPause"
                                   onclick="itemPause(${ item.id})"/>
                        </c:when>
                        <c:otherwise>
                            <input type="button" value="开始"
                                   class="btn btn-primary" id="btnPause"
                                   onclick="itemPause(${ item.id })"/>
                        </c:otherwise>
                    </c:choose>
                    <input type="button" class="btn" value="编辑" id="btnEdit"
                           onclick="itemEdit(${ item.id })"/>
                    <input type="button" class="btn" value="删除" name="btnDel" id="btnDel"
                           onclick="itemDel(${ item.id })"/>
                </td>
            </tr>

        </c:forEach>
    </table>

    <div><input type="checkbox" id="allCheck">全选
        <input type="button" value="${runText}" id="run" class="btn btn-info">
        <input type="hidden" id="hidden_run" value="${ isRun }">
        <!-- Button trigger modal -->
        <button type="button" class="btn btn-info" onclick="itemAdd()">
            添加
        </button>
        <input type="button" value="${allStartText}"
               class="btn btn-info"
               id="allStart">
    </div>
    <%@include file="dialog_add.html" %>
    <%@include file="dialog_del.html" %>
</div>
<script>

    var timeOut = false;

    $(document).ready(function () {
        console.log("页面初始化...");
        toastr.options.positionClass = 'toast-top-center';
        toastr.options.timeOut = 1000;

        var value = $('#hidden_run').val();
        var btnRun = $('#run');
        if (value == '0') {
            btnRun.val('启动');
            timeOut = true;
        } else {
            btnRun.val('停止');
            timeOut = false;
        }
        runCycle();
    });
    $(function () {
        var allCheck = $('#allCheck');//id # class .
        allCheck.click(function () {
            var isAllChecked = allCheck.is(':checked');
            console.log("是否全选:" + isAllChecked);
            $('input[name=cb]:checkbox').each(function () {
//                $(this).prop('checked', isAllChecked);
                //attr 会导致第一次能够全选，第二次不能够全选 可以使用prop
                this.checked = isAllChecked;
            });
        });

        $('#run').click(function () {
            $.ajax({
                url: 'action_run',
                success: function (data) {
                    if (data == '1') {
                        timeOut = false;
                        $('#run').val('停止');
                    } else {
                        $('#run').val('停止...');
                        timeOut = true;
                        setTimeout(function () {
                            $('#run').val('启动');
                            $('#mTable').find('tr').each(function () {
                                var tdArr = $(this).children();
                                var imgTd = tdArr.eq(1).find('img#img_status');
                                imgTd.attr('src', '../files/img/status_red.png');
                            });
                        }, 4000);
                    }
                    runCycle();
                }
            });
        });

        $('#allStart').click(function () {
            console.log('allStart');
            $.ajax({
                url: 'action_all_start',
                success: function (data) {
                    $(this).val(data)
                    setTimeout(function () {
                        window.location.reload();
                    }, 500);
                }
            });

        });
        //保存修改内容
        $('#submit_save').click(function () {
            console.log("保存");
            var data = getFormData($('#form'));
            data['url'] = $('#dialog_url').val();
            var id = $('#dialog_id').val();
            var url = 'action_add/' + id;
            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                success: function (result) {
                    console.log("result = " + result);
                    $('#myModal').modal('hide');
                    if (result == '1') {
                        toastr.success("保存成功");
                        setTimeout(function () {
                            window.location.reload();
                        }, 500);
                    } else {
                        toastr.error("保存失败");
                    }
                }
            });
        });

        $('#submit_del').click(function () {
            console.log("删除");
            var id = $('#hidden_del_id').val();
            $.ajax({
                url: 'action_del/' + id,
                success: function (result) {
                    console.log("result = " + result);
                    $('#modalDel').modal('hide');
                    if (result == '1') {
                        toastr.success("删除成功");
                        setTimeout(function () {
                            window.location.reload();
                        }, 500);
                    } else {
                        toastr.error("删除失败");
                    }
                }
            });
        });


    });

    function runCycle() {
        if (timeOut) return;
        refreshTimes();
        setTimeout(runCycle, 1000);
    }

    function refreshTimes() {
        $.ajax({
            url: 'get_access_times',
            success: function (data) {
                var json = JSON.parse(data);
                $('#mTable').find('tr').each(function () {
                    var tdArr = $(this).children();
                    var accTime = tdArr.eq(7);
                    var id = tdArr.eq(8).find('input#hidden_id').val();
                    var is_green = tdArr.eq(8).find('input#hidden_is_green');
                    var imgTd = tdArr.eq(1).find('img#img_status');
                    var mId = '_' + id;
                    if (json[mId] != null) {
                        if (json[mId]['id'] == id) {
                            console.log("is_green = " + is_green.val() + " id = " + id);
                            accTime.text(json[mId]['times']);
                            if (is_green.val() == '1') {
                                console.log("set green ... id = " + id);
                                imgTd.attr('src', '../files/img/status_green.png');
                            } else {
                                console.log("set red ... id = " + id);
                                imgTd.attr('src', '../files/img/status_red.png');
                            }
                        } else {
                            imgTd.attr('src', '../files/img/status_red.png');
                        }
                    }
                });
            }
        });
    }


    function itemPause(_id) {
        console.log("暂停" + _id);
        $.ajax({
            url: 'action_pause/' + _id,
            success: function (result) {
                if (result == '1') {
                    toastr.success("暂停成功");
                    setTimeout(function () {
                        window.location.reload();
                    }, 1000);
                } else {
                    toastr.error("操作失败");
                }
            }
        });
    }

    function itemDel(_id) {
        var hi = $('#hidden_del_id');
        hi.val(_id);
        console.log("id = " + hi.val());
        $('#modalDel').modal('show');
    }


    function itemAdd() {
        console.log("添加");
        $('#myModalLabel').text('添加');
        $('#dialog_title').val('');
        $('#dialog_url').val('http://');
        $('#dialog_access_time_interval').val(5);
        $('#dialog_time_out').val(10);
        $('#dialog_access_time').val(1);
        $('#dialog_id').val(0);
        $('#myModal').modal('show');
    }

    function itemEdit(_id) {
        console.log("id = " + _id);
        $('#myModalLabel').text('编辑');
        var json = eval(${jsonLists});
        for (var i = 0; i < json.length; i++) {
            var item = json[i];
            if (json[i].id == _id) {
                console.log(item.title_name);
                $('#dialog_title').val(item.title_name);
                $('#dialog_url').val(item.url);
                $('#dialog_access_time_interval').val(item.access_time_interval);
                $('#dialog_time_out').val(item.time_out);
                $('#dialog_access_time').val(item.access_time);
                $('#dialog_id').val(item.id);
                $('#myModal').modal('show');
                break;
            }
        }
    }

    function getFormData(form) {
        var data = form.serialize();
        data = decodeURIComponent(data);
        var arr = data.split('&');
        var item, key, value, newData = {};
        for (var i = 0; i < arr.length; i++) {
            item = arr[i].split('=');
            key = item[0];
            value = item[1];
            newData[key] = value;
        }
        return newData;
    }

</script>
</body>
</html>
